<template>
  <div>
    <CommonSearch
      v-model="tableConfig.searchParams"
      :config="searchConfig"
    ></CommonSearch>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-input
          placeholder="请输入部门名称"
          @input="changeDeptName"
          @clear="tree.filter('')"
          v-model="deptName"
          clearable
          prefix-icon="el-icon-search"
        >
        </el-input>
        <el-tree
          :data="departmentData"
          default-expand-all
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          @node-click="nodeClick"
          ref="tree"
        >
        </el-tree>
      </el-col>
      <el-col :span="20">
        <CommonTable :config="tableConfig" ref="commonTable">
          <template #status="{ row }">
            <el-tooltip
              :content="`状态:${row.status == 1 ? '启用' : '禁用'}`"
              placement="top"
            >
              <el-switch
                @click="handlerStatus(row)"
                :value="row.status"
                active-color="#13ce66"
                inactive-color="#dcdfe6"
                active-value="1"
                inactive-value="0"
              >
              </el-switch>
            </el-tooltip>
          </template>
        </CommonTable>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue';
import { CREATE, UPDATE, DELETE, QUERY, EXPORT, RESET } from '@/utils/Const';

import {
	getUserListApi,
	createUserApi,
	updateUserApi,
	deleteUserApi,
	getDeptListApi,
	getRolesOrPostsApi
} from '@/api/system.api';
import { listToMenu, dataAdaptive, debounce } from '@/utils/tools';
import { isPassword, isMobile, isEmail } from '@/utils/validate';

export default {
	name : 'User',
	setup () {
		let Instance = getCurrentInstance().proxy;
		let commonTable = null;
		let tree = null;
		let deptList = ref([]);
		let data = reactive({
			departmentData : [],
			deptName : '',
			searchConfig : {
				handlerSearch () {
					return commonTable.fetchData({ isResetPageNumber : true });
				},
				form : [
					{
						type : 'text',
						label : '用户名称:',
						placeholder : '请输入用户名称',
						key : 'userName'
					},
					{
						type : 'text',
						label : '手机号码:',
						placeholder : '请输入手机号码',
						key : 'phonenumber'
					},
					{
						type : 'select',
						label : '状态:',
						placeholder : '请选择状态',
						key : 'status',
						options : [
							{
								value : '',
								label : '全部'
							},
							{
								value : '1',
								label : '正常'
							},
							{
								value : '0',
								label : '停用'
							}
						]
					},
					{
						type : 'daterange',
						commentsName : 'datePicker',
						label : '创建时间:',
						placeholder : '请选择创建时间',
						key : 'params'
					}
				]
			},
			tableConfig : {
				searchParams : {},
				reqApiMethod : getUserListApi,
				operateWidth : 170,
				handlerOperate : async (payload, row) => {
					data.formConfig.type = payload.butType;
					let formConfig = {
						data : Array.isArray(row) ? row[0] : '',
						...data.formConfig
					};

					let names = [];
					let ids = [];
					switch (payload.butType) {
					case CREATE:
						// eslint-disable-next-line no-case-declarations
						let res = await getRolesOrPosts();
						data.formConfig.form[5].options = res.posts;
						data.formConfig.form[6].options = res.roles;
						Instance.$hyDialogForm(data.formConfig);
						break;
					case DELETE:
						row.forEach((item) => {
							names.push(item.userName);
							ids.push(item.userId);
						});
						Instance.$hyConfirm({
							subTitle : `是否确定删除【${names.join()}】`,
							callback : async (done) => {
								await deleteUserApi({ ids : ids.join() });
								done();
								commonTable.fetchData();
							}
						});
						break;
					case RESET:
						Instance.$prompt('请输入密码', '提示', {
							confirmButtonText : '确定',
							cancelButtonText : '取消',
							inputPlaceholder : '请输入6到18位密码',
							inputPattern :
                  /(?=.*\d)(?=.*[a-zA-Z\W])|(?=.*[a-zA-Z])(?=.*[\d\W])|(?=.*\W)(?=.*[a-zA-Z0-9]).{6,18}/,
							inputErrorMessage :
                  '请输入6到18位密码(数字,字母，特殊字符，任意2种组合)',
							beforeClose : async (action, instance, done) => {
								if (action === 'confirm') {
									instance.confirmButtonLoading = true;
									instance.confirmButtonText = '执行中...';
									await updateUserApi({
										userId : row[0].userId,
										password : instance.inputValue
									});
									instance.confirmButtonLoading = false;
									done();
									commonTable.fetchData();
								} else {
									done();
								}
							}
						});
						break;
					case UPDATE:
						console.log(row);
						// eslint-disable-next-line no-case-declarations
						let r = await getRolesOrPosts();
						data.formConfig.form[5].options = r.posts;
						data.formConfig.form[6].options = r.roles;
						data.formConfig.form[5].defaultValue = row[0].posts;
						data.formConfig.form[6].defaultValue = row[0].roles;
						Instance.$hyDialogForm(formConfig);
						break;
					case QUERY:
						formConfig.disabled = true;
						Instance.$hyDialogForm(formConfig);
						break;
					}
				},
				columns : [
					{
						type : 'index'
					},
					{
						type : 'selection'
					},
					{
						title : '用户名称',
						field : 'userName'
					},
					{
						title : '用户昵称',
						field : 'nickName'
					},
					{
						title : '部门',
						field : 'dept',
						formatter : (value) => {
							if (value) {
								return value.deptName;
							}
						}
					},
					{
						title : '手机号',
						field : 'phonenumber'
					},
					{
						title : '状态',
						field : 'status',
						formatter : (value) => {
							if (Number(value) === 0) {
								return '停用';
							}
							return '正常';
						}
					},
					{
						title : '创建时间',
						field : 'createTime'
					}
				],
				globalOperate : [
					{
						butType : CREATE,
						name : '新增',
						color : 'primary',
						role : [],
						icon : 'el-icon-plus'
					},
					{
						butType : UPDATE,
						name : '修改',
						enable : '1',
						color : 'success',
						role : [],
						icon : 'el-icon-edit'
					},
					{
						butType : QUERY,
						name : '查看',
						enable : '1',
						color : 'warning',
						role : [],
						icon : 'el-icon-edit'
					},
					{
						butType : DELETE,
						name : '删除',
						enable : '2',
						color : 'danger',
						role : [],
						icon : 'el-icon-delete'
					},
					{
						butType : EXPORT,
						name : '导出',
						color : 'warning',
						role : [],
						icon : 'el-icon-download'
					}
				],
				operate : [
					{
						butType : UPDATE,
						type : 'text',
						name : '修改',
						role : [],
						icon : 'el-icon-edit'
					},
					{
						butType : DELETE,
						type : 'text',
						name : '删除',
						role : [],
						icon : 'el-icon-delete'
					},
					{
						butType : RESET,
						type : 'text',
						name : '重置',
						role : [],
						icon : 'el-icon-key'
					}
				]
			},
			formConfig : {
				top : '20px',
				type : '',
				async handlerSubmit (params) {
					switch (data.formConfig.type) {
					case CREATE:
						await createUserApi(params);
						break;
					case UPDATE:
						await updateUserApi(params);
						break;
					}
					return commonTable.fetchData();
				},
				form : [
					{
						type : 'text',
						label : '用户Id',
						key : 'userId',
						hide : true
					},
					{
						type : 'text',
						label : '用户昵称:',
						placeholder : '请输入用户昵称',
						maxlength : 10,
						key : 'nickName',
						rules : [
							{ required : true, message : '请输入用户昵称', trigger : 'blur' }
						]
					},
					{
						type : 'text',
						label : '用户名称:',
						placeholder : '请输入用户名称',
						maxlength : 10,
						key : 'userName',
						rules : [
							{ required : true, message : '请输入用户名称', trigger : 'blur' }
						]
					},
					{
						type : 'password',
						label : '用户密码:',
						placeholder : '请输入用户密码',
						maxlength : 16,
						key : 'password',
						rules : [
							{
								required : true,
								validator : (rule, value, callback) => {
									if (!isPassword(value)) {
										callback(
											new Error('数字,字母，特殊字符，任意2种组合(6-16)位')
										);
									} else {
										callback();
									}
								}
							}
						]
					},
					{
						type : 'treeselect',
						label : '归属部门:',
						placeholder : '请选择归属部门',
						reeselectData : deptList,
						dataAdaptiveMap : {
							deptId : 'id',
							deptName : 'label'
						},
						key : 'deptId'
					},
					{
						type : 'select',
						multiple : true,
						label : '岗位:',
						placeholder : '请选择岗位',
						key : 'postIds',
						options : []
					},
					{
						type : 'select',
						multiple : true,
						label : '角色:',
						placeholder : '请选择角色',
						key : 'roleIds',
						options : []
					},
					{
						type : 'text',
						label : '手机号码:',
						placeholder : '请输入手机号码',
						key : 'phonenumber',
						rules : [
							{
								validator : (rule, value, callback) => {
									if (!value) {
										callback();
									} else if (!isMobile(value)) {
										callback(new Error('请输入11位合法的手机号码'));
									} else {
										callback();
									}
								},
								trigger : 'blur'
							}
						]
					},
					{
						type : 'text',
						label : '邮箱:',
						placeholder : '请输入邮箱',
						key : 'email',
						rules : [
							{
								validator : (rule, value, callback) => {
									if (!value) {
										callback();
									} else if (!isEmail(value)) {
										callback(new Error('请输入合法的邮箱'));
									} else {
										callback();
									}
								},
								trigger : 'blur'
							}
						]
					},
					{
						type : 'radio',
						label : '状态:',
						key : 'status',
						defaultValue : '1',
						options : [
							{
								value : '1',
								label : '正常'
							},
							{
								value : '0',
								label : '停用'
							}
						]
					},
					{
						type : 'radio',
						label : '用户性别:',
						key : 'sex',
						defaultValue : '1',
						options : [
							{
								value : '1',
								label : '男'
							},
							{
								value : '0',
								label : '女'
							}
						]
					},
					{
						type : 'textarea',
						label : '备注:',
						placeholder : '请输入内容',
						key : 'remark',
						maxlength : 100
					}
				]
			}
		});

		const handlerStatus = (row) => {
			let { status, userName } = row;
			Instance.$hyConfirm({
				subTitle : `是否${status == 0 ? '启用' : '禁用'}【${userName}】`,
				callback : (done) => {
					done();
					row.status = !status;
					commonTable.fetchData();
				}
			});
		};

		onMounted(() => {
			commonTable = Instance.$refs['commonTable'];
			tree = Instance.$refs['tree'];
		});

		let filterNode = (value, payload) => {
			if (!value) return true;
			return payload.label.indexOf(value) !== -1;
		};

		let init = async () => {
			let res = await getDeptListApi();
			deptList.value = listToMenu({ list : res.list, idKey : 'deptId' });
			data.departmentData = dataAdaptive(deptList.value, {
				deptId : 'id',
				deptName : 'label'
			});
		};

		let nodeClick = (params) => {
			data.tableConfig.searchParams.deptId = params.id;
			commonTable.fetchData();
		};

		let changeDeptName = debounce((val) => {
			tree.filter(val);
		}, 300);

		let getRolesOrPosts = async () => {
			let res = await getRolesOrPostsApi();
			let posts = [];
			let roles = [];
			res.posts.forEach((item) => {
				posts.push({
					label : item.postName,
					value : item.postId
				});
			});

			res.roles.forEach((item) => {
				roles.push({
					label : item.roleName,
					value : item.roleId
				});
			});
			return {
				posts,
				roles
			};
		};

		init();

		return {
			tree,
			filterNode,
			nodeClick,
			changeDeptName,
			handlerStatus,
			...toRefs(data)
		};
	}
};
</script>

<style lang="scss" scoped></style>
